var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require("fs");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var suff=[".png",".apk",".doc",".xml",".jpg",".jpeg",".mp3",".mp4",".pdf",".docx",".txt"];
var DATA=null;

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
DATA= JSON.parse(fs.readFileSync(__dirname+"/config.json"));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(DATA.SDIR));
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if(req.body.userId!=DATA.RECEIVEID||req.body.ncheck!="d2l0aHRpbWU="){

        res.send(404);
        return;
    }
    if (req.method == 'OPTIONS') {


        res.send(200); /让options请求快速返回/
    }
    else {

        next();
    }
});
app.use('/', indexRouter);
app.use('/users', usersRouter);

app.post("/files",function (req,res) {

    let dirs=[];
    let code = DATA.RECEIVEID;
    let filepath = DATA.SDIR;
    if(req.body.userId==code&&req.body.ncheck=="d2l0aHRpbWU="){

        let files = fs.readdirSync(filepath);

        for(let i =0;i<files.length;i++){
            let fp = path.resolve(filepath, files[i])
            let stat = fs.statSync(fp);
            if(files[i]==".DS_Store"){

                continue;
            }

            let suf = path.extname(files[i]);
            if(!suff.includes(suf)){
                suf=".none";
            }
            if(stat.isFile()) {

                let item = {fname: files[i], suffix:"p"+suf,mt:stat.mtime};
                dirs.push(item);
            }
        }
        res.json({ls:dirs});
    }
});
app.listen(DATA.PORT);
module.exports = app;
